<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<div class="module-filter">
					<label style="margin-right: 10px">{{ $t('brand_data.startDate') }}</label>
					<el-date-picker v-model="params.startDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
						:placeholder="$t('brand_data.startDateLabel')" :disabled-date="beforeOptions"></el-date-picker>
				</div>
				<div class="module-filter">
					<label style="margin-right: 10px">{{ $t('brand_data.endDate') }}</label>
					<el-date-picker v-model="params.endDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
						:placeholder="$t('brand_data.endDateLabel')" :disabled-date="backOptions"></el-date-picker>
				</div>
				<div class="module-filter">
					<label style="margin-right: 10px;width: 100px">{{ $t('artwork_data.creatorName') }}</label>
					<div class="el-select el-select--default">
						<el-input type="text" v-model="params.creatorName" clearable></el-input>
					</div>
				</div>
				<div class="module-filter">
					<label style="margin-right: 10px;width: 100px">{{ $t('artwork_data.movieName') }}</label>
					<div class="el-select el-select--default">
						<el-input type="text" v-model="params.movieName" clearable></el-input>
					</div>
				</div>
				<div class="module-filter btns">
					<el-button type="primary" icon="el-icon-search" @click="upsearch">{{ $t('table_data.searchText') }}</el-button>
					<el-button @click="reset">{{ $t('table_data.resetText') }}</el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
			<div class="top-panel">
				<el-button type="primary" icon="el-icon-plus" @click="add">{{ $t('table_data.addText') }}</el-button>
			</div>
			<scTable ref="table" :apiObj="apiObj" row-key="id" stripe border :params="sendParams" :hideSetting="true"
				@sortChange="sortChange" :sortType="direction" width="100%">
				<el-table-column :label="$t('activity_form.title')" width="auto">
					<template #default="scope">
						{{ scope.row.festivalName[$i18n.locale] }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('movie_data.fullMovieTitle')" width="auto">
					<template #default="scope">
						{{ scope.row.thumbnailName?scope.row.thumbnailName[$i18n.locale]:'' }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('artwork_data.creatorName')" width="auto">
					<template #default="scope">
						{{ scope.row.creatorName?scope.row.creatorName[$i18n.locale]:'' }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('banner_data.class1')" prop="itemCount" width="auto"></el-table-column>
				<el-table-column :label="$t('activity_list.specialItems')" width="auto">
					<template #default="scope">
						{{ scope.row.specialItem?$t('table_data.yes'):$t('table_data.no') }}
					</template>
				</el-table-column>
				<el-table-column :label="$t('activity_list.stime')" prop="startTime" width="auto"></el-table-column>
				<el-table-column :label="$t('activity_list.etime')" prop="endTime" width="auto"></el-table-column>
				<el-table-column :label="$t('activity_list.status')" width="auto">
					<template #default="scope">
						<span v-if="scope.row.status==1" class="colorGrayText">{{ $t('activity_list.status1') }}</span>
						<span v-if="scope.row.status==2" class="colorBlueText">{{ $t('activity_list.status2') }}</span>
						<span v-if="scope.row.status==3" class="colorGrayText">{{ $t('activity_list.status3') }}</span>
						<span v-if="scope.row.status==4" class="colorRedText">{{ $t('activity_list.status4') }}</span>
						<span v-if="scope.row.status==5" class="colorGreenText">{{ $t('activity_list.status5') }}</span>
					</template>
				</el-table-column>
				<el-table-column :label="$t('table_data.createAt')" prop="createdTime" width="auto" sortable></el-table-column>
				<el-table-column :label="$t('table_data.operate')" width="auto">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small" @click="table_detail(scope.row, scope.$index)">{{ $t('table_data.detail') }}</el-button>
							<el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">{{ $t('table_data.edit') }}</el-button>
							<!-- <el-button text type="danger" size="small" @click="table_del(scope.row, scope.$index)">{{ $t('table_data.del') }}</el-button> -->
							<!-- <el-button text size="small" @click="table_export(scope.row.festivalId)">{{ $t('activity_form.exportCode') }}</el-button> -->
							<el-button text size="small" @click="modelValue=true;festivalId=scope.row.festivalId">{{$t('activity_form.exportCode')}}</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<sCDialog :modelValue="modelValue" :showFullscreen="false" @closeDialog="openUpload" :closeOnClickModal="false">
			<template v-slot:header>
				<div class="header">
					{{ $t('activity_form.exportCode') }}
				</div>
			</template>
			<div>
				<el-form :model="scDialogData" label-width="auto" label-position="right" style="display: block;">
					<el-form-item :label="$t('components.export.numInput')">
						<el-input type="number" v-model="number" clearable></el-input>
					</el-form-item>
				</el-form>
			</div>
			<template v-slot:footer>
				<el-button type="primary" :disabled="isExport" @click="createQRCode">{{ $t('short_data.step.confirm') }}</el-button>
			</template>
		</sCDialog>
		<!-- <scTable style="display: none;" ref="activity" :apiObj="exportObj" row-key="id" stripe border :params="sendParams" :hideSetting="true"
			@sortChange="sortChange" :sortType="direction" width="100%" id="activity">
			<el-table-column :label="$t('brand_data.name')" prop="name" width="auto"></el-table-column>
			<el-table-column :label="$t('brand_data.address')" prop="officialAddress" width="auto"></el-table-column>
			<el-table-column :label="$t('brand_data.email')" prop="officialEmail" width="auto"></el-table-column>
			<el-table-column :label="$t('brand_data.phone')" width="auto">
				<template #default="scope">
					{{ scope.row.phoneCode+'-'+scope.row.phoneNo }}
				</template>
			</el-table-column>
			<el-table-column :label="$t('brand_data.quantity')" prop="cinemaQuantity" width="auto"></el-table-column>
			<el-table-column :label="$t('table_data.createAt')" prop="createAt" width="auto" sortable></el-table-column>
		</scTable> -->
	</el-container>
	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>
</template>

<script>
import saveDialog from "./client/save";
import sCDialog from "@/components/scDialog"
// import { exportTable } from "@/utils/export.js";
// import VueCsvImport from 'vue-csv-import';
import Papa from "papaparse";

export default {
  name: "client",
  components: {
		sCDialog,
    saveDialog
  },
  data() {
    return {
			isExport: false,
			number: 1000,
			festivalId: '',
			modelValue: false,
      direction: "sortDirection",
      langList: [
        {
          name: "简体中文",
          value: "zh_CN"
        },
        {
          name: "繁體中文",
          value: "zh_TW"
        },
        {
          name: "English",
          value: "en_US"
        },
        {
          name: "日本語",
          value: "ja_JP"
        }
      ],
      classList: [
        {
          name: this.$t("artwork_data.classification.class1"),
          value: 11
        },
        {
          name: this.$t("artwork_data.classification.class2"),
          value: 12
        },
        {
          name: this.$t("artwork_data.classification.class3"),
          value: 13
        },
        {
          name: this.$t("artwork_data.classification.class4"),
          value: 14
        },
        {
          name: this.$t("artwork_data.classification.class5"),
          value: 21
        },
        {
          name: this.$t("artwork_data.classification.class7"),
          value: 15
        },
        {
          name: this.$t("artwork_data.classification.class6"),
          value: 29
        }
      ],
      tonghList: [
        {
          name: this.$t("table_data.currency.dollar"),
          value: 2
        },
        {
          name: this.$t("table_data.currency.rmb"),
          value: 3
        },
        {
          name: this.$t("table_data.currency.jpy"),
          value: 1
        }
      ],
      movieData: [],
      theatreData: [],
      dialog: {
        save: false
      },
      search: {
        keyword: ""
      },
      apiObj: {},
      selection: [],
      searchKey: null,
      params: {
        // currency: null,
        // movieId: null,
        // category: null,
        startDate: null,
        endDate: null,
        language: null
      },
      sendParams: {},
      exportNum: 2,
      exportObj: ""
    };
  },
  async created() {
    this.apiObj = this.$API.activity.getList;
  },
  methods: {
    closeTag() {
      const tagList = this.$store.state.viewTags.viewTags;
      const tag = this.$route;
      const nowTagIndex = tagList.findIndex(
        item => item.fullPath == tag.fullPath
      );
      this.$store.commit("removeViewTags", tag);
      this.$store.commit("removeIframeList", tag);
      this.$store.commit("removeKeepLive", tag.name);

      const leftView = tagList[nowTagIndex - 1];
      if (leftView) {
        this.$router.push(leftView);
      } else {
        this.$router.push("/");
      }
    },
    reset() {
      this.params.startDate = null;
      this.params.endDate = null;
      this.params.creatorName = null;
      this.params.movieName = null;
      this.upsearch();
    },
    upsearch() {
      Object.assign(this.sendParams, this.params);
      // if (this.sendParams.startDate)
      //   this.sendParams.startDate = this.$TOOL.getLocalTime(
      //     9,
      //     this.params.startDate,
      //     true
      //   );
      // if (this.sendParams.endDate)
      //   this.sendParams.endDate = this.$TOOL.getLocalTime(
      //     9,
      //     this.params.endDate,
      //     true
      //   );
      this.$refs.table.upData(this.sendParams);
    },
    //增加
    add() {
      this.$router.push({
        path: "/activityTable/client/save",
        query: { type: "add", id: "add" }
      });
    },
    //编辑
    table_edit(row) {
      this.$router.push({
        path: "/activityTable/client/save",
        query: { type: "edit", id: row.festivalId }
      });
      // this.dialog.save = true
      // this.$nextTick(() => {
      // 	this.$refs.saveDialog.open('edit').setData(row)
      // })
    },
    // 详情
    table_detail(row) {
      this.$router.push({
        path: "/activityTable/client/save",
        query: { type: "detail", id: row.festivalId }
      });
      // this.dialog.save = true
      // this.$nextTick(() => {
      // 	this.$refs.saveDialog.open('edit').setData(row)
      // })
    },
		// 生成code
		createQRCode() {
			let data = {
				"apikey": null,
				"festivalId": this.festivalId,
				"artworkId": null,
				"number": this.number
			};
			this.isExport = true;
			this.$API.activity.createQRCode.post(data).then(res => {
				if(res.code == "OK") {
					this.$message.success('Success');
					this.table_export(this.festivalId);
				}
			})
		},
    // 导出
    async table_export(id) {
      this.$API.activity.exportActivityUrl.get(id).then(res => {
				this.exportCSV(res.data);
      });

      // this.exportObj = this.$API.activity.exportActivityUrl;
      // exportTable("activity", "活动二维码");
    },
    // 导出csv
    async exportCSV(data) {
			const cdata = data.map(n=>[n])
      const csv = Papa.unparse(cdata);

      // 创建一个下载链接
      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.setAttribute("href", url);
      link.setAttribute("download", `QRCODE-${this.$TOOL.dateFormat(new Date(), "yyyy-MM-dd")}.csv`);
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
			this.isExport = false;
    },
    //删除
    async table_del(row, index) {
      console.log(index);
      this.$confirm(
        this.$t("table_data.deltips1"),
        this.$t("table_data.tips"),
        {
          confirmButtonText: this.$t("table_data.editText"),
          cancelButtonText: this.$t("table_data.cancelText"),
          type: "warning"
        }
      )
        .then(async () => {
          var res = await this.$API.brand.delBrand.delete(row.brandId);
          if (res.code == "OK") {
            //这里选择刷新整个表格 OR 插入/编辑现有表格数据
            this.$refs.table.upData(this.params);
            this.$message.success(this.$t("table_data.delsucc"));
          } else {
            this.$alert(res.message, this.$t("table_data.tips"), {
              type: "error"
            });
          }
        })
        .catch(() => {
          // this.$message({
          // 	type: 'info',
          // 	message: 'cancel'
          // });
        });
    },
    //批量删除
    async batch_del() {
      this.$confirm(
        `${this.$t("table_data.deltips1")} ${this.selection.length} ${this.$t(
          "table_data.deltips2"
        )}`,
        this.$t("table_data.tips"),
        {
          type: "warning"
        }
      )
        .then(() => {
          const loading = this.$loading();
          this.selection.forEach(item => {
            this.$refs.table.tableData.forEach((itemI, indexI) => {
              if (item.id === itemI.id) {
                this.$refs.table.tableData.splice(indexI, 1);
              }
            });
          });
          loading.close();
          this.$message.success(this.$t("table_data.operasucc"));
        })
        .catch(() => {});
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection;
    },
    //本地更新数据
    handleSuccess(data, mode) {
      if (mode == "add") {
        data.id = new Date().getTime();
        this.$refs.table.tableData.unshift(data);
      } else if (mode == "edit") {
        this.$refs.table.tableData
          .filter(item => item.id === data.id)
          .forEach(item => {
            Object.assign(item, data);
          });
      }
    },
		openUpload() {
			this.modelValue = !this.modelValue;
		},
    beforeOptions(v) {
      if (!this.params.endDate) return false;
      return v.getTime() > new Date(this.params.endDate).getTime(); //  - 86400000是否包括当天
    },
    backOptions(v) {
      return v.getTime() < new Date(this.params.startDate).getTime(); //  - 86400000是否包括当天
    },
  }
};
</script>

<style scoped>
.module-filter {
  margin-right: 10px;
}

.el-header {
  --el-header-height: auto;
}

.header {
	font-size: 22px;
}

.formBox {
	display: flex;
}

.left-panel {
  flex-wrap: wrap;
  line-height: 50px;
}

.top-panel {
  margin: 10px;
}

.scTable {
  height: calc(100% - 60px) !important;
}

.el-main.nopadding {
  margin: 0 10px;
}

.el-header {
  margin: 10px;
  border-radius: 4px;
}

.el-form-item {
	display: flex;
	flex-direction: column;
}

@media only screen and (max-width: 820px) and (min-width: 768px) {
  .module-filter {
    flex: 0 0 30%;
    display: flex;
    flex-direction: column;
    margin: 0 10px;
  }
  .btns {
    margin: 10px;
    width: 340px;
    flex-direction: row;
  }
}
</style>
